/*
 * Copyright (c) 2008 Benoit Bouchez, Nicolas Giard
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.noocodecommit.wicket.stuff.jquery.plugin.ui.datepicker;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.apache.wicket.Request;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.WicketRuntimeException;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.calldecorator.CancelEventIfNoAjaxDecorator;

import com.noocodecommit.wicket.stuff.jquery.behavior.AbstractDefaultJQBehavior;
import com.noocodecommit.wicket.stuff.jquery.exception.CannotApplyJQBehaviorException;
import com.noocodecommit.wicket.stuff.jquery.plugin.IJQPluginComponent;
import com.noocodecommit.wicket.stuff.jquery.plugin.JQPlugin;

/**
 * Ajax behavior for datepicker date select handle<br>
 * 
 * @author Benoit Bouchez
 * 
 */
public abstract class OnDateSelectBehavior extends AbstractDefaultJQBehavior
{
	private JQDatePicker datepicker;

	/**
	 * Constructor 
	 * this behavior must be added to the datepicker's parent textfield
	 * 
	 * @param datepicker
	 *            datepicker reference
	 */
	public OnDateSelectBehavior(JQDatePicker datepicker)
	{
		this.datepicker = datepicker;
	}

	protected void respond(AjaxRequestTarget target)
	{
		Request req = RequestCycle.get().getRequest();
		//System.out.println(req.getParameter("date"));
		SimpleDateFormat sdf = new SimpleDateFormat(req.getParameter("format"));
		//System.out.println(req.getParameter("format"));
		if(this.datepicker.getOptions().isRangeSelect())
		{
			String[] dates = req.getParameter("date").split(this.datepicker.getOptions().getRangeSeparator());
			try
			{
				this.datepicker.setStartDate(sdf.parse(dates[0]));
				this.datepicker.setEndDate(sdf.parse(dates[1]));
			}
			catch (ParseException e)
			{
				e.printStackTrace();
			}
		}else
		{
			try
			{
				this.datepicker.setStartDate(sdf.parse(req.getParameter("date")));
			}
			catch (ParseException e)
			{
				e.printStackTrace();
			}
		}
		// -- force no focus after ajax call
		target.focusComponent(null);
		this.onSelect(target);
	}

	protected CharSequence getCallbackScript(boolean onlyTargetActivePage)
	{
		return generateCallbackScript("wicketAjaxGet('" + getCallbackUrl(onlyTargetActivePage) + "&date=' + date + '&format=' + $.datepicker.regional"+this.datepicker.getPlugin().getRegional()+".dateFormat + ''");
	}

	@Override
	protected IAjaxCallDecorator getAjaxCallDecorator()
	{
		return new CancelEventIfNoAjaxDecorator(super.getAjaxCallDecorator());
	}

	@Override
	protected void onBind()
	{
		// Wicket Binding
		super.onBind();		
		// Check component binding
		if(!this.datepicker.getClass().equals(JQDatePicker.class))
		{
			throw new CannotApplyJQBehaviorException(OnDateBeforeShowBehavior.class, this.getComponent().getClass(), JQDatePicker.class);
		}
		// Plugin ajax support & options clone export only if PLUGIN_INIT_ONCE
		JQDatePicker component = this.datepicker;
		if(component.getPlugin().getInitMode() == JQPlugin.PLUGIN_INIT_ONCE)
		{
			if (component.getPlugin().attachComponentForDocumentReadySupportingAjax((IJQPluginComponent) component))
			{
				try
				{
					component.setOptions((JQDatePickerOptions) component.getPlugin().getOptions().clone());
				}
				catch (CloneNotSupportedException e)
				{
					throw new WicketRuntimeException(e);
				}
			}
		}
		// JQuery binding to callback function
		this.datepicker.getOptions().setOnSelectScript(this.datepicker.getOptions().getOnSelectScript() + this.getCallbackScript(false).toString());
	}

	/**
	 * Called when a date select event is fired
	 * 
	 * @param target
	 */
	public abstract void onSelect(AjaxRequestTarget target);

	/**
	 * Gets the behavior's datepicker reference
	 * @return this behavior's current datepicker
	 */
	public JQDatePicker getDatepicker()
	{
		return datepicker;
	}
}
